package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-24
 * Time: 22:02
 */

/**
 * 服务器的流程
 * 1:读取请求并解析
 * 2:根据请求计算响应
 * 3:把响应写回到客户端
 */
public class UdpEchoServe {

  private   DatagramSocket socket = null;
    public UdpEchoServe(int port) throws SocketException {

        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动!");
        while(true){
            DatagramPacket requestPaket = new DatagramPacket(new byte[4096],4096);
            //requestPacket表示收到的数据报
            socket.receive(requestPaket);
            String request = new String(requestPaket.getData(),0,requestPaket.getLength());
           String response =  process(request);
            //执行计算逻辑
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),0,response.getBytes().length,
                    requestPaket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s :%d]   res=%s ,resp=%s\n",
                    requestPaket.getAddress(),requestPaket.getPort(),
                    request,response);
        }

    }
    public String process  (String response){
        return response;
    }
     public static void main(String[] args) throws IOException {
        UdpEchoServe serve = new UdpEchoServe(9090);
        serve.start();

    }
}
